document.addEventListener('DOMContentLoaded', function() {
    // 暂时禁用AOS动画库，因为在浏览器插件环境中可能导致内容闪烁
    // AOS.init({
    //     duration: 800,
    //     easing: 'ease-in-out',
    //     once: true,
    //     offset: 50,
    //     delay: 0
    // });
    
    // 确保内容立即可见
    document.body.style.opacity = '1';
    
    // 选项卡切换功能
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabPanes = document.querySelectorAll('.tab-pane');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            const tabId = button.getAttribute('data-tab');
            
            // 移除所有活动状态
            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabPanes.forEach(pane => pane.classList.remove('active'));
            
            // 添加当前活动状态
            button.classList.add('active');
            document.getElementById(tabId).classList.add('active');
            
            // 移除切换动画效果，避免内容消失
            // const activePane = document.getElementById(tabId);
            // activePane.style.opacity = '0';
            // activePane.style.transform = 'translateY(10px)';
            
            // setTimeout(() => {
            //     activePane.style.transition = 'all 0.3s ease';
            //     activePane.style.opacity = '1';
            //     activePane.style.transform = 'translateY(0)';
            // }, 10);
        });
    });
    
    // JSON美化功能
    const jsonInput = document.getElementById('json-input');
    const jsonOutput = document.getElementById('json-output');
    const formatBtn = document.getElementById('json-format');
    const compressBtn = document.getElementById('json-compress');
    const copyBtn = document.getElementById('json-copy');
    
    formatBtn.addEventListener('click', () => {
        try {
            const json = JSON.parse(jsonInput.value);
            jsonOutput.value = JSON.stringify(json, null, 2);
            showMessage('JSON格式化成功', 'success');
        } catch (error) {
            showMessage('JSON格式错误: ' + error.message, 'error');
        }
    });
    
    compressBtn.addEventListener('click', () => {
        try {
            const json = JSON.parse(jsonInput.value);
            jsonOutput.value = JSON.stringify(json);
            showMessage('JSON压缩成功', 'success');
        } catch (error) {
            showMessage('JSON格式错误: ' + error.message, 'error');
        }
    });
    
    copyBtn.addEventListener('click', () => {
        if (jsonOutput.value) {
            navigator.clipboard.writeText(jsonOutput.value)
                .then(() => showMessage('已复制到剪贴板', 'success'))
                .catch(err => showMessage('复制失败: ' + err, 'error'));
        } else {
            showMessage('没有可复制的内容', 'error');
        }
    });
    
    // 时间戳转换功能
    const timestampInput = document.getElementById('timestamp-input');
    const dateInput = document.getElementById('date-input');
    const dateOutput = document.getElementById('date-output');
    const timestampOutput = document.getElementById('timestamp-output');
    const currentTimeOutput = document.getElementById('current-time-output');
    
    document.getElementById('timestamp-to-date').addEventListener('click', () => {
        const timestamp = timestampInput.value.trim();
        if (!timestamp) {
            showMessage('请输入时间戳', 'error');
            return;
        }
        
        try {
            let date;
            // 判断是秒还是毫秒
            if (timestamp.length === 10) {
                date = new Date(parseInt(timestamp) * 1000);
            } else {
                date = new Date(parseInt(timestamp));
            }
            
            if (isNaN(date.getTime())) {
                throw new Error('无效的时间戳');
            }
            
            dateOutput.textContent = date.toLocaleString();
            showMessage('转换成功', 'success');
        } catch (error) {
            showMessage('转换失败: ' + error.message, 'error');
        }
    });
    
    document.getElementById('date-to-timestamp').addEventListener('click', () => {
        if (!dateInput.value) {
            showMessage('请选择日期', 'error');
            return;
        }
        
        try {
            const date = new Date(dateInput.value);
            const timestamp = Math.floor(date.getTime() / 1000);
            timestampOutput.textContent = `秒级时间戳: ${timestamp}\n毫秒级时间戳: ${timestamp * 1000}`;
            showMessage('转换成功', 'success');
        } catch (error) {
            showMessage('转换失败: ' + error.message, 'error');
        }
    });
    
    document.getElementById('current-timestamp').addEventListener('click', () => {
        const now = new Date();
        const timestamp = Math.floor(now.getTime() / 1000);
        currentTimeOutput.textContent = `当前时间: ${now.toLocaleString()}\n秒级时间戳: ${timestamp}\n毫秒级时间戳: ${timestamp * 1000}`;
        showMessage('获取成功', 'success');
    });
    
    // 翻译功能
    const translateInput = document.getElementById('translate-input');
    const translateOutput = document.getElementById('translate-output');
    const translateBtn = document.getElementById('translate-btn');
    const sourceLang = document.getElementById('source-lang');
    const targetLang = document.getElementById('target-lang');
    
    translateBtn.addEventListener('click', () => {
        const text = translateInput.value.trim();
        if (!text) {
            showMessage('请输入要翻译的文本', 'error');
            return;
        }
        
        // 显示加载状态
        translateBtn.innerHTML = '<span class="loading"></span>翻译中...';
        translateBtn.disabled = true;
        
        // 使用免费的翻译API
        translateText(text, sourceLang.value, targetLang.value)
            .then(result => {
                translateOutput.textContent = result;
                showMessage('翻译成功', 'success');
            })
            .catch(error => {
                showMessage('翻译失败: ' + error.message, 'error');
            })
            .finally(() => {
                translateBtn.innerHTML = '翻译';
                translateBtn.disabled = false;
            });
    });
    
    // 二维码生成功能
    const qrcodeInput = document.getElementById('qrcode-input');
    const qrcodeOutput = document.getElementById('qrcode-output');
    const qrcodeSize = document.getElementById('qrcode-size');
    const generateBtn = document.getElementById('generate-qrcode');
    const downloadBtn = document.getElementById('download-qrcode');
    
    generateBtn.addEventListener('click', async () => {
        const text = qrcodeInput.value.trim();
        if (!text) {
            showMessage('请输入要生成二维码的内容', 'error');
            return;
        }
        
        try {
            // 显示加载状态
            generateBtn.innerHTML = '<span class="loading"></span>生成中...';
            generateBtn.disabled = true;
            
            // 清空之前的二维码
            qrcodeOutput.innerHTML = '';
            
            // 获取二维码尺寸
            const size = parseInt(qrcodeSize.value);
            
            // 调用API生成二维码
            const response = await fetch(`https://tapi.xuejss.com/xue/tool/generateQrCode/?text=${encodeURIComponent(text)}&size=${size}`);
            const result = await response.json();
            
            if (result.code === 1 && result.data && result.data.qr_code) {
                // 创建图片元素显示二维码
                const img = document.createElement('img');
                img.src = result.data.qr_code;
                img.alt = '生成的二维码';
                img.style.maxWidth = '100%';
                img.style.height = 'auto';
                
                qrcodeOutput.appendChild(img);
                downloadBtn.classList.remove('hidden');
                showMessage('二维码生成成功', 'success');
            } else {
                throw new Error(result.msg || '生成二维码失败');
            }
        } catch (error) {
            showMessage('二维码生成失败: ' + error.message, 'error');
        } finally {
            // 恢复按钮状态
            generateBtn.innerHTML = '生成二维码';
            generateBtn.disabled = false;
        }
    });
    
    downloadBtn.addEventListener('click', () => {
        const img = qrcodeOutput.querySelector('img');
        if (img) {
            // 创建下载链接
            const link = document.createElement('a');
            link.download = 'qrcode.png';
            link.href = img.src;
            link.click();
            showMessage('二维码下载成功', 'success');
        }
    });
    
    // 辅助函数
    function showMessage(message, type) {
        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `message ${type}`;
        messageEl.textContent = message;
        
        // 添加动画效果
        messageEl.style.opacity = '0';
        messageEl.style.transform = 'translateY(-10px)';
        
        // 找到当前活动的选项卡
        const activeTab = document.querySelector('.tab-pane.active');
        
        // 将消息添加到活动选项卡的顶部
        const firstChild = activeTab.firstChild;
        if (firstChild) {
            activeTab.insertBefore(messageEl, firstChild);
        } else {
            activeTab.appendChild(messageEl);
        }
        
        // 触发动画
        setTimeout(() => {
            messageEl.style.transition = 'all 0.3s ease';
            messageEl.style.opacity = '1';
            messageEl.style.transform = 'translateY(0)';
        }, 10);
        
        // 3秒后自动移除
        setTimeout(() => {
            messageEl.style.transition = 'all 0.3s ease';
            messageEl.style.opacity = '0';
            messageEl.style.transform = 'translateY(-10px)';
            
            setTimeout(() => {
                messageEl.remove();
            }, 300);
        }, 3000);
    }
    
    // 添加按钮点击波纹效果
    function addRippleEffect(button) {
        button.addEventListener('click', function(e) {
            const ripple = document.createElement('span');
            const rect = this.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = e.clientX - rect.left - size / 2;
            const y = e.clientY - rect.top - size / 2;
            
            ripple.style.width = ripple.style.height = size + 'px';
            ripple.style.left = x + 'px';
            ripple.style.top = y + 'px';
            ripple.classList.add('ripple');
            
            this.appendChild(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    }
    
    // 为所有按钮添加波纹效果
    document.querySelectorAll('button').forEach(addRippleEffect);
    
    // 添加输入框聚焦效果
    document.querySelectorAll('input, textarea, select').forEach(element => {
        element.addEventListener('focus', function() {
            // 移除transform效果以避免文字模糊
            // this.parentElement.style.transform = 'scale(1.02)';
            // this.parentElement.style.transition = 'transform 0.2s ease';
        });
        
        element.addEventListener('blur', function() {
            // 移除transform效果以避免文字模糊
            // this.parentElement.style.transform = 'scale(1)';
        });
    });
    
    // 翻译函数 - 使用免费API
    async function translateText(text, from, to) {
        // 这里使用一个简单的翻译API示例
        // 实际应用中可能需要替换为其他API或使用浏览器内置翻译功能
        
        // 如果源语言和目标语言相同，直接返回原文
        if (from === to) {
            return text;
        }
        
        try {
            // 使用MyMemory免费翻译API
            const langPair = from === 'auto' ? `autodetect|${to}` : `${from}|${to}`;
            const response = await fetch(`https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=${langPair}`);
            
            if (!response.ok) {
                throw new Error('翻译请求失败');
            }
            
            const data = await response.json();
            
            if (data.responseStatus === 200) {
                return data.responseData.translatedText;
            } else {
                throw new Error(data.responseDetails || '翻译失败');
            }
        } catch (error) {
            // 如果API失败，返回一个模拟翻译结果
            return `[翻译结果] ${text} (${from} → ${to})`;
        }
    }
    
    // 书签同步功能
    const syncMethod = document.getElementById('sync-method');
    const exportSection = document.getElementById('export-section');
    const importSection = document.getElementById('import-section');
    const cloudSection = document.getElementById('cloud-section');
    const bookmarksCount = document.getElementById('bookmarks-count');
    const foldersCount = document.getElementById('folders-count');
    const recentBookmarksList = document.getElementById('recent-bookmarks-list');
    
    // 切换同步方式
    syncMethod.addEventListener('change', () => {
        // 隐藏所有部分
        exportSection.classList.add('hidden');
        importSection.classList.add('hidden');
        cloudSection.classList.add('hidden');
        
        // 显示选中的部分
        const method = syncMethod.value;
        if (method === 'export') {
            exportSection.classList.remove('hidden');
        } else if (method === 'import') {
            importSection.classList.remove('hidden');
        } else if (method === 'cloud') {
            cloudSection.classList.remove('hidden');
        }
    });
    
    // 获取书签统计信息
    function updateBookmarksStats() {
        // 检查浏览器环境，支持Chrome和QQ浏览器
        const isExtensionEnvironment = (typeof chrome !== 'undefined' && chrome.bookmarks && chrome.bookmarks.getTree) || 
                                      (typeof browser !== 'undefined' && browser.bookmarks && browser.bookmarks.getTree);
        
        if (isExtensionEnvironment) {
            // 使用适当的浏览器API
            const bookmarksAPI = (typeof chrome !== 'undefined' && chrome.bookmarks) ? chrome.bookmarks : browser.bookmarks;
            
            bookmarksAPI.getTree((bookmarkTree) => {
                let bookmarks = 0;
                let folders = 0;
                const recentBookmarks = [];
                
                function countItems(nodes) {
                    nodes.forEach(node => {
                        if (node.children) {
                            folders++;
                            countItems(node.children);
                        } else {
                            bookmarks++;
                            // 收集最近的书签
                            if (node.dateAdded) {
                                recentBookmarks.push({
                                    title: node.title,
                                    url: node.url,
                                    dateAdded: node.dateAdded
                                });
                            }
                        }
                    });
                }
                
                countItems(bookmarkTree);
                
                // 更新统计信息
                bookmarksCount.textContent = bookmarks;
                foldersCount.textContent = folders;
                
                // 显示最近的书签
                recentBookmarks.sort((a, b) => b.dateAdded - a.dateAdded);
                recentBookmarksList.innerHTML = '';
                
                // 只显示前5个最近的书签
                recentBookmarks.slice(0, 5).forEach(bookmark => {
                    const li = document.createElement('li');
                    li.innerHTML = `<a href="${bookmark.url}" target="_blank">${bookmark.title}</a>`;
                    recentBookmarksList.appendChild(li);
                });
            });
        } else {
            // 在非扩展环境中显示模拟数据
            bookmarksCount.textContent = '0';
            foldersCount.textContent = '0';
            recentBookmarksList.innerHTML = '<li>书签功能仅在浏览器扩展环境中可用</li>';
        }
    }
    
    // 导出书签
    document.getElementById('export-bookmarks').addEventListener('click', () => {
        // 检查浏览器环境，支持Chrome和QQ浏览器
        const isExtensionEnvironment = (typeof chrome !== 'undefined' && chrome.bookmarks && chrome.bookmarks.getTree) || 
                                      (typeof browser !== 'undefined' && browser.bookmarks && browser.bookmarks.getTree);
        
        if (isExtensionEnvironment) {
            // 使用适当的浏览器API
            const bookmarksAPI = (typeof chrome !== 'undefined' && chrome.bookmarks) ? chrome.bookmarks : browser.bookmarks;
            
            bookmarksAPI.getTree((bookmarkTree) => {
                const exportData = {
                    exportDate: new Date().toISOString(),
                    browser: navigator.userAgent,
                    bookmarks: bookmarkTree
                };
                
                // 创建下载链接
                const dataStr = JSON.stringify(exportData, null, 2);
                const dataBlob = new Blob([dataStr], {type: 'application/json'});
                const url = URL.createObjectURL(dataBlob);
                
                const downloadLink = document.createElement('a');
                downloadLink.href = url;
                downloadLink.download = `bookmarks_${new Date().toISOString().slice(0, 10)}.json`;
                downloadLink.click();
                
                URL.revokeObjectURL(url);
                
                document.getElementById('export-output').textContent = '书签已成功导出';
                showMessage('书签导出成功', 'success');
            });
        } else {
            document.getElementById('export-output').textContent = '书签导出功能仅在浏览器扩展环境中可用';
            showMessage('书签导出功能仅在浏览器扩展环境中可用', 'error');
        }
    });
    
    // 导入书签
    document.getElementById('import-bookmarks').addEventListener('click', () => {
        const fileInput = document.getElementById('import-file');
        const file = fileInput.files[0];
        
        if (!file) {
            showMessage('请选择要导入的书签文件', 'error');
            return;
        }
        
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = JSON.parse(e.target.result);
                
                // 确认导入
                if (confirm('确定要导入这些书签吗？这可能会创建重复的书签。')) {
                    importBookmarks(data.bookmarks);
                }
            } catch (error) {
                showMessage('文件格式错误: ' + error.message, 'error');
            }
        };
        
        reader.readAsText(file);
    });
    
    // 递归导入书签
    function importBookmarks(nodes, parentId = undefined) {
        // 检查浏览器环境，支持Chrome和QQ浏览器
        const isExtensionEnvironment = (typeof chrome !== 'undefined' && chrome.bookmarks && chrome.bookmarks.create) || 
                                      (typeof browser !== 'undefined' && browser.bookmarks && browser.bookmarks.create);
        
        if (isExtensionEnvironment) {
            // 使用适当的浏览器API
            const bookmarksAPI = (typeof chrome !== 'undefined' && chrome.bookmarks) ? chrome.bookmarks : browser.bookmarks;
            
            // 如果没有指定parentId，则先获取书签栏ID
            if (!parentId) {
                bookmarksAPI.getTree((bookmarkTree) => {
                    const rootChildren = bookmarkTree[0].children;
                    let bookmarksBarId = null;
                    let otherBookmarksId = null;
                    
                    // 查找书签栏和其他书签的ID
                    rootChildren.forEach(folder => {
                        if (folder.title === "书签栏" || folder.title === "Bookmarks bar") {
                            bookmarksBarId = folder.id;
                        } else if (folder.title === "其他书签" || folder.title === "Other bookmarks") {
                            otherBookmarksId = folder.id;
                        }
                    });
                    
                    // 如果nodes是根节点（包含children），则直接处理其子节点
                    if (nodes && nodes.length > 0 && nodes[0] && nodes[0].children) {
                        // 直接处理根节点的子节点
                        processImportedNodes(nodes[0].children, bookmarksBarId, otherBookmarksId);
                    } else {
                        // 否则直接处理nodes
                        processImportedNodes(nodes, bookmarksBarId, otherBookmarksId);
                    }
                });
            } else {
                // 如果已指定parentId，直接导入
                processImportedNodes(nodes, parentId);
            }
        } else {
            showMessage('书签导入功能仅在浏览器扩展环境中可用', 'error');
        }
    }
    
    // 处理导入的节点
    function processImportedNodes(nodes, bookmarksBarId, otherBookmarksId) {
        // 使用适当的浏览器API
        const bookmarksAPI = (typeof chrome !== 'undefined' && chrome.bookmarks) ? chrome.bookmarks : browser.bookmarks;
        
        nodes.forEach(node => {
            if (node.children) {
                // 如果是文件夹
                if (node.title === "其他书签" || node.title === "Other bookmarks") {
                    // 如果是"其他书签"文件夹，将其内容直接导入到书签栏
                    if (node.children && bookmarksBarId) {
                        processImportedNodes(node.children, bookmarksBarId);
                    }
                } else if (node.title === "书签栏" || node.title === "Bookmarks bar") {
                    // 如果是"书签栏"文件夹，将其内容直接导入到书签栏
                    if (node.children && bookmarksBarId) {
                        processImportedNodes(node.children, bookmarksBarId);
                    }
                } else {
                    // 创建其他文件夹
                    bookmarksAPI.create({
                        title: node.title,
                        parentId: bookmarksBarId
                    }, (newFolder) => {
                        // 递归导入子项
                        processImportedNodes(node.children, newFolder.id);
                    });
                }
            } else if (node.url) {
                // 创建书签到书签栏
                bookmarksAPI.create({
                    title: node.title,
                    url: node.url,
                    parentId: bookmarksBarId
                });
            }
        });
    }
    
    // 清除所有书签
    function clearAllBookmarks(callback) {
        // 检查浏览器环境，支持Chrome和QQ浏览器
        const isExtensionEnvironment = (typeof chrome !== 'undefined' && chrome.bookmarks && chrome.bookmarks.getTree && chrome.bookmarks.removeTree) || 
                                      (typeof browser !== 'undefined' && browser.bookmarks && browser.bookmarks.getTree && browser.bookmarks.removeTree);
        
        if (isExtensionEnvironment) {
            // 使用适当的浏览器API
            const bookmarksAPI = (typeof chrome !== 'undefined' && chrome.bookmarks) ? chrome.bookmarks : browser.bookmarks;
            
            bookmarksAPI.getTree((bookmarkTree) => {
                // 获取书签栏和其他书签文件夹
                const bookmarkFolders = bookmarkTree[0].children;
                let foldersToRemove = [];
                
                // 收集所有需要删除的文件夹（保留"书签栏"和"其他书签"等根文件夹）
                bookmarkFolders.forEach(folder => {
                    if (folder.children && folder.children.length > 0) {
                        // 递归收集所有子文件夹和书签
                        const collectItems = (node) => {
                            if (node.children) {
                                node.children.forEach(child => {
                                    collectItems(child);
                                });
                            }
                            // 只添加非根文件夹和书签到删除列表
                            if (folder.id !== node.id) {
                                foldersToRemove.push(node.id);
                            }
                        };
                        collectItems(folder);
                    }
                });
                
                // 删除所有收集到的文件夹和书签
                let removedCount = 0;
                const totalToRemove = foldersToRemove.length;
                
                if (totalToRemove === 0) {
                    // 如果没有书签需要删除，直接调用回调
                    callback();
                    return;
                }
                
                // 递归删除函数
                const removeItems = () => {
                    if (foldersToRemove.length > 0) {
                        const itemId = foldersToRemove.pop();
                        bookmarksAPI.removeTree(itemId, () => {
                            removedCount++;
                            // 继续删除下一个
                            removeItems();
                        });
                    } else {
                        // 所有项目已删除，调用回调
                        callback();
                    }
                };
                
                // 开始删除
                removeItems();
            });
        } else {
            showMessage('清除书签功能仅在浏览器扩展环境中可用', 'error');
            if (callback) callback();
        }
    }
    
    // 获取浏览器类型
    function getBrowserType() {
        const userAgent = navigator.userAgent;
        if (userAgent.includes('Chrome') && !userAgent.includes('Edg') && !userAgent.includes('QQBrowser')) {
            return 'chrome';
        } else if (userAgent.includes('QQBrowser')) {
            return 'qq';
        } else if (userAgent.includes('Edg')) {
            return 'edge';
        } else if (userAgent.includes('Firefox')) {
            return 'firefox';
        } else {
            return 'unknown';
        }
    }

    // 备份到云端
    document.getElementById('backup-to-cloud').addEventListener('click', () => {
        // 检查是否已登录
        getUserAuth((auth) => {
            if (!auth) {
                showMessage('请先登录后再进行云端备份', 'error');
                return;
            }
            
            // 检查浏览器环境，支持Chrome和QQ浏览器
            const isExtensionEnvironment = (typeof chrome !== 'undefined' && chrome.bookmarks && chrome.bookmarks.getTree) || 
                                          (typeof browser !== 'undefined' && browser.bookmarks && browser.bookmarks.getTree);
            
            if (isExtensionEnvironment) {
                // 使用适当的浏览器API
                const bookmarksAPI = (typeof chrome !== 'undefined' && chrome.bookmarks) ? chrome.bookmarks : browser.bookmarks;
                
                bookmarksAPI.getTree(async (bookmarkTree) => {
                    const browserType = getBrowserType();
                    const backupData = {
                        user_id: auth.user_id,
                        sign: auth.token,
                        browser_info: navigator.userAgent,
                        browser_type: browserType, // 添加浏览器类型标识
                        bookmarks: JSON.stringify(bookmarkTree)
                    };
                    
                    try {
                        const response = await fetch('http://tapi.xuejss.com/xue/tool/bookmarksBackup', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(backupData)
                        });
                        
                        const result = await response.json();
                        
                        if (result.code === 1) {
                            document.getElementById('cloud-output').textContent = `书签已成功备份到云端 (备份ID: ${result.data.backup_id})`;
                            showMessage('书签备份到云端成功', 'success');
                        } else {
                            showMessage('备份失败: ' + (result.msg || '未知错误'), 'error');
                        }
                    } catch (error) {
                        console.error('备份请求失败:', error);
                        showMessage('备份请求失败: ' + error.message, 'error');
                    }
                });
            } else {
                document.getElementById('cloud-output').textContent = '云端备份功能仅在浏览器扩展环境中可用';
                showMessage('云端备份功能仅在浏览器扩展环境中可用', 'error');
            }
        });
    });
    
    // 从云端恢复
    document.getElementById('restore-from-cloud').addEventListener('click', () => {
        // 检查是否已登录
        getUserAuth((auth) => {
            if (!auth) {
                showMessage('请先登录后再进行云端恢复', 'error');
                return;
            }
            
            // 发送恢复请求
            (async () => {
                try {
                    const requestData = {
                        user_id: auth.user_id,
                        sign: auth.token,
                        browser_type: getBrowserType()
                    };
                    
                    const response = await fetch('http://tapi.xuejss.com/xue/tool/bookmarksRestore', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(requestData)
                    });
                    
                    const result = await response.json();
                    
                    if (result.code === 1 && result.data) {
                        // 显示备份信息
                        const backupDate = result.data.backup_date;
                        const backupBrowserType = result.data.browser_type || 'unknown';
                        const currentBrowserType = getBrowserType();
                        
                        // 检查浏览器类型是否匹配
                        if (backupBrowserType !== currentBrowserType) {
                            const browserNames = {
                                'chrome': 'Chrome浏览器',
                                'qq': 'QQ浏览器',
                                'edge': 'Edge浏览器',
                                'firefox': 'Firefox浏览器',
                                'unknown': '未知浏览器'
                            };
                            
                            const backupBrowserName = browserNames[backupBrowserType] || '未知浏览器';
                            const currentBrowserName = browserNames[currentBrowserType] || '当前浏览器';
                            
                            showMessage(`此备份来自${backupBrowserName}，不能在${currentBrowserName}中恢复`, 'error');
                            return;
                        }
                        
                        if (confirm(`确定要恢复 ${backupDate} 的备份吗？这将删除所有现有书签并替换为备份的书签。`)) {
                            try {
                                // 解析书签数据
                                let bookmarksData;
                                console.log('原始书签数据类型:', typeof result.data.bookmarks);
                                console.log('原始书签数据:', result.data.bookmarks);
                                
                                if (typeof result.data.bookmarks === 'string') {
                                    // 尝试多种解析方法
                                    try {
                                        // 方法1: 直接JSON解析
                                        bookmarksData = JSON.parse(result.data.bookmarks);
                                        console.log('方法1: 直接JSON解析成功');
                                    } catch (e) {
                                        console.log('方法1失败，尝试方法2');
                                        try {
                                            // 方法2: 处理双重编码的字符串
                                            let processedStr = result.data.bookmarks;
                                            
                                            // 移除外层引号
                                            if (processedStr.startsWith('"') && processedStr.endsWith('"')) {
                                                processedStr = processedStr.slice(1, -1);
                                            }
                                            
                                            // 处理转义字符
                                            processedStr = processedStr.replace(/\\"/g, '"');
                                            processedStr = processedStr.replace(/\\\\/g, '\\');
                                            
                                            // 尝试解析处理后的字符串
                                            bookmarksData = JSON.parse(processedStr);
                                            console.log('方法2: 处理转义字符后JSON解析成功');
                                        } catch (e2) {
                                            console.log('方法2失败，尝试方法3');
                                            try {
                                                // 方法3: 使用Function构造函数（比eval更安全）
                                                let funcStr = result.data.bookmarks;
                                                
                                                // 移除外层引号
                                                if (funcStr.startsWith('"') && funcStr.endsWith('"')) {
                                                    funcStr = funcStr.slice(1, -1);
                                                }
                                                
                                                // 处理转义字符
                                                funcStr = funcStr.replace(/\\"/g, '"');
                                                funcStr = funcStr.replace(/\\\\/g, '\\');
                                                
                                                // 使用Function构造函数
                                                const parseFunction = new Function('return ' + funcStr);
                                                bookmarksData = parseFunction();
                                                console.log('方法3: Function构造函数解析成功');
                                            } catch (e3) {
                                                console.log('方法3失败，尝试方法4');
                                                try {
                                                    // 方法4: 使用eval作为最后手段
                                                    let evalStr = result.data.bookmarks;
                                                    
                                                    // 移除外层引号
                                                    if (evalStr.startsWith('"') && evalStr.endsWith('"')) {
                                                        evalStr = evalStr.slice(1, -1);
                                                    }
                                                    
                                                    // 处理转义字符
                                                    evalStr = evalStr.replace(/\\"/g, '"');
                                                    evalStr = evalStr.replace(/\\\\/g, '\\');
                                                    
                                                    // 使用eval
                                                    bookmarksData = eval('(' + evalStr + ')');
                                                    console.log('方法4: eval解析成功');
                                                } catch (e4) {
                                                    console.error('所有解析方法都失败:', e, e2, e3, e4);
                                                    console.error('原始数据:', result.data.bookmarks);
                                                    
                                                    // 最后尝试：如果数据是数组格式，尝试提取数组部分
                                                    try {
                                                        const arrayMatch = result.data.bookmarks.match(/\[.*\]/s);
                                                        if (arrayMatch) {
                                                            const arrayStr = arrayMatch[0];
                                                            bookmarksData = JSON.parse(arrayStr);
                                                            console.log('方法5: 提取数组部分解析成功');
                                                        } else {
                                                            throw new Error('无法提取数组部分');
                                                        }
                                                    } catch (e5) {
                                                        console.error('方法5也失败:', e5);
                                                        throw new Error('无法解析书签数据格式');
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    bookmarksData = result.data.bookmarks;
                                    console.log('书签数据已经是对象格式，无需解析');
                                }
                                
                                // 先清除所有现有书签，然后导入新书签
                                clearAllBookmarks(() => {
                                    importBookmarks(bookmarksData);
                                    document.getElementById('cloud-output').textContent = `书签已从云端恢复 (${backupDate})`;
                                    showMessage('书签从云端恢复成功', 'success');
                                });
                            } catch (parseError) {
                                console.error('解析书签数据失败:', parseError);
                                console.error('原始数据:', result.data.bookmarks);
                                showMessage('书签数据格式错误', 'error');
                            }
                        }
                    } else {
                        showMessage('恢复失败: ' + (result.msg || '没有找到云端备份'), 'error');
                    }
                } catch (error) {
                    console.error('恢复请求失败:', error);
                    showMessage('恢复请求失败: ' + error.message, 'error');
                }
            })();
        });
    });
    
    // 查看云端备份列表
    document.getElementById('list-cloud-backups').addEventListener('click', () => {
        getUserAuth((auth) => {
            if (!auth) {
                showMessage('请先登录微信账号', 'error');
                return;
            }
            
            document.getElementById('cloud-output').textContent = '正在获取备份列表...';
            
            // 发送获取备份列表请求
            (async () => {
                try {
                    const requestData = {
                        user_id: auth.user_id,
                        sign: auth.token,
                        browser_type: getBrowserType()
                    };
                    
                    const response = await fetch('http://tapi.xuejss.com/xue/tool/bookmarksList', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(requestData)
                    });
                    
                    const result = await response.json();
                    
                    if (result.code === 1 && result.data && result.data.length > 0) {
                        // 显示备份列表
                        const backupList = document.getElementById('backup-list-items');
                        backupList.innerHTML = '';
                        
                        const browserNames = {
                            'chrome': 'Chrome',
                            'qq': 'QQ浏览器',
                            'edge': 'Edge',
                            'firefox': 'Firefox',
                            'unknown': '未知'
                        };
                        
                        result.data.forEach((backup, index) => {
                            const browserType = backup.browser_type || 'unknown';
                            const browserName = browserNames[browserType] || '未知';
                            
                            const li = document.createElement('li');
                            li.innerHTML = `
                                <div class="backup-item-info">
                                    <div class="backup-date">${backup.backup_date}</div>
                                    <div class="backup-browser">
                                        来源: <span class="backup-browser-type browser-${browserType}">${browserName}</span>
                                    </div>
                                </div>
                            `;
                            
                            // 如果备份的浏览器类型与当前浏览器类型相同，添加点击恢复功能
                            if (browserType === getBrowserType()) {
                                li.style.cursor = 'pointer';
                                li.addEventListener('click', () => {
                                    if (confirm(`确定要恢复 ${backup.backup_date} 的备份吗？这将删除所有现有书签并替换为备份的书签。`)) {
                                        restoreFromSpecificBackup(backup);
                                    }
                                });
                            } else {
                                li.style.opacity = '0.6';
                                li.title = `此备份来自${browserName}，不能在当前浏览器中恢复`;
                            }
                            
                            backupList.appendChild(li);
                        });
                        
                        document.getElementById('backup-list').classList.remove('hidden');
                        document.getElementById('cloud-output').textContent = `找到 ${result.data.length} 个备份`;
                    } else {
                        document.getElementById('backup-list').classList.add('hidden');
                        document.getElementById('cloud-output').textContent = '没有找到云端备份';
                    }
                } catch (error) {
                    console.error('获取备份列表失败:', error);
                    document.getElementById('backup-list').classList.add('hidden');
                    document.getElementById('cloud-output').textContent = '获取备份列表失败: ' + error.message;
                }
            })();
        });
    });
    
    // 从特定备份恢复书签
    function restoreFromSpecificBackup(backupData) {
        try {
            // 解析书签数据
            let bookmarksData;
            console.log('原始书签数据类型:', typeof backupData.bookmarks);
            console.log('原始书签数据:', backupData.bookmarks);
            
            if (typeof backupData.bookmarks === 'string') {
                // 尝试多种解析方法
                try {
                    // 方法1: 直接JSON解析
                    bookmarksData = JSON.parse(backupData.bookmarks);
                    console.log('方法1: 直接JSON解析成功');
                } catch (e) {
                    console.log('方法1失败，尝试方法2');
                    try {
                        // 方法2: 处理双重编码的字符串
                        let processedStr = backupData.bookmarks;
                        
                        // 移除外层引号
                        if (processedStr.startsWith('"') && processedStr.endsWith('"')) {
                            processedStr = processedStr.slice(1, -1);
                        }
                        
                        // 处理转义字符
                        processedStr = processedStr.replace(/\\"/g, '"');
                        processedStr = processedStr.replace(/\\\\/g, '\\');
                        
                        // 尝试解析处理后的字符串
                        bookmarksData = JSON.parse(processedStr);
                        console.log('方法2: 处理转义字符后JSON解析成功');
                    } catch (e2) {
                        console.log('方法2失败，尝试方法3');
                        try {
                            // 方法3: 使用Function构造函数（比eval更安全）
                            let funcStr = backupData.bookmarks;
                            
                            // 移除外层引号
                            if (funcStr.startsWith('"') && funcStr.endsWith('"')) {
                                funcStr = funcStr.slice(1, -1);
                            }
                            
                            // 处理转义字符
                            funcStr = funcStr.replace(/\\"/g, '"');
                            funcStr = funcStr.replace(/\\\\/g, '\\');
                            
                            // 使用Function构造函数
                            const parseFunction = new Function('return ' + funcStr);
                            bookmarksData = parseFunction();
                            console.log('方法3: Function构造函数解析成功');
                        } catch (e3) {
                            console.log('方法3失败，尝试方法4');
                            try {
                                // 方法4: 使用eval作为最后手段
                                let evalStr = backupData.bookmarks;
                                
                                // 移除外层引号
                                if (evalStr.startsWith('"') && evalStr.endsWith('"')) {
                                    evalStr = evalStr.slice(1, -1);
                                }
                                
                                // 处理转义字符
                                evalStr = evalStr.replace(/\\"/g, '"');
                                evalStr = evalStr.replace(/\\\\/g, '\\');
                                
                                // 使用eval
                                bookmarksData = eval('(' + evalStr + ')');
                                console.log('方法4: eval解析成功');
                            } catch (e4) {
                                console.error('所有解析方法都失败:', e, e2, e3, e4);
                                console.error('原始数据:', backupData.bookmarks);
                                throw new Error('无法解析书签数据格式');
                            }
                        }
                    }
                }
            } else {
                bookmarksData = backupData.bookmarks;
                console.log('书签数据已经是对象格式，无需解析');
            }
            
            // 先清除所有现有书签，然后导入新书签
            clearAllBookmarks(() => {
                importBookmarks(bookmarksData);
                document.getElementById('cloud-output').textContent = `书签已从云端恢复 (${backupData.backup_date})`;
                showMessage('书签从云端恢复成功', 'success');
            });
        } catch (parseError) {
            console.error('解析书签数据失败:', parseError);
            console.error('原始数据:', backupData.bookmarks);
            showMessage('书签数据格式错误', 'error');
        }
    }
    
    // 初始化书签统计（仅在Chrome API可用时执行）
    if (typeof chrome !== 'undefined' && chrome.bookmarks && chrome.bookmarks.getTree) {
        updateBookmarksStats();
    }
    
    // Chrome存储API检查
    
    // 检查Chrome存储API是否可用
    function isChromeStorageAvailable() {
        return typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local;
    }
    
    // 保存用户信息到本地存储
    function saveUserInfo(userInfo) {
        if (isChromeStorageAvailable()) {
            chrome.storage.local.set({wechatUserInfo: userInfo}, () => {
                showLoginSuccess(userInfo);
            });
        } else {
            // 备选方案：使用localStorage
            try {
                localStorage.setItem('wechatUserInfo', JSON.stringify(userInfo));
                showLoginSuccess(userInfo);
            } catch (error) {
                console.error('保存用户信息失败:', error);
                showLoginSuccess(userInfo); // 即使保存失败也显示登录成功
            }
        }
    }
    
    // 获取用户认证信息
    function getUserAuth(callback) {
        getUserInfo((userInfo) => {
            if (userInfo && userInfo.userid && userInfo.token) {
                callback({
                    user_id: userInfo.userid,
                    token: userInfo.token
                });
            } else {
                callback(null);
            }
        });
    }

    // 从本地存储获取用户信息
    function getUserInfo(callback) {
        if (isChromeStorageAvailable()) {
            chrome.storage.local.get(['wechatUserInfo'], (result) => {
                callback(result && result.wechatUserInfo ? result.wechatUserInfo : null);
            });
        } else {
            // 备选方案：使用localStorage
            try {
                const userInfo = localStorage.getItem('wechatUserInfo');
                callback(userInfo ? JSON.parse(userInfo) : null);
            } catch (error) {
                console.error('获取用户信息失败:', error);
                callback(null);
            }
        }
    }
    
    // 清除本地存储中的用户信息
    function clearUserInfo(callback) {
        if (isChromeStorageAvailable()) {
            chrome.storage.local.remove(['wechatUserInfo'], callback);
        } else {
            // 备选方案：使用localStorage
            try {
                localStorage.removeItem('wechatUserInfo');
                if (callback) callback();
            } catch (error) {
                console.error('清除用户信息失败:', error);
                if (callback) callback();
            }
        }
    }
    
    // 微信登录功能
    let loginPollingInterval = null;
    let currentLoginCode = null;
    document.getElementById('get-qrcode-btn').addEventListener('click', getWeChatQRCode);
    
    // 刷新二维码按钮事件
    document.getElementById('refresh-qrcode').addEventListener('click', getWeChatQRCode);
    
    // 退出登录按钮事件
    document.getElementById('logout-btn').addEventListener('click', logout);
    
    // 获取微信登录二维码
    async function getWeChatQRCode() {
        try {
            // 显示加载状态
            const qrcodeContainer = document.getElementById('qrcode-container');
            const qrcodeImage = document.getElementById('qrcode-image');
            const loginSuccess = document.getElementById('login-success');
            
            qrcodeContainer.classList.add('hidden');
            qrcodeImage.classList.remove('hidden');
            loginSuccess.classList.add('hidden');
            
            document.getElementById('qrcode-img').innerHTML = '<div class="loading-spinner"></div>';
            document.getElementById('login-status').textContent = '正在获取二维码...';
            
            // 请求获取二维码
            const response = await fetch('https://tapi.xuejss.com/xue/user/getIncreatqrcode');
            const result = await response.json();
            
            console.log('获取二维码结果:', result); // 添加调试日志
            
            if (result.code === 200 && result.data) {
                // 显示二维码
                const qrcodeData = result.data.xcxqrcode || result.data.qrcode;
                if (qrcodeData) {
                    document.getElementById('qrcode-img').innerHTML = `<img src="${qrcodeData}" alt="微信登录二维码">`;
                    document.getElementById('login-status').textContent = '请使用微信扫描二维码登录';
                    
                    // 保存登录码用于轮询
                    currentLoginCode = result.data.scene || result.data.loginCode;
                    
                    if (currentLoginCode) {
                        // 开始轮询登录状态
                        startLoginPolling();
                    } else {
                        throw new Error('未获取到登录码');
                    }
                } else {
                    throw new Error('未获取到二维码数据');
                }
            } else {
                throw new Error(result.msg || '获取二维码失败');
            }
        } catch (error) {
            console.error('获取二维码失败:', error);
            showMessage('获取二维码失败: ' + error.message, 'error');
            document.getElementById('qrcode-img').innerHTML = '';
            document.getElementById('login-status').textContent = '获取二维码失败，请重试';
        }
    }
    
    // 开始轮询登录状态
    function startLoginPolling() {
        // 清除之前的轮询
        if (loginPollingInterval) {
            clearInterval(loginPollingInterval);
        }
        
        // 设置轮询间隔为3秒
        loginPollingInterval = setInterval(async () => {
            try {
                if (!currentLoginCode) {
                    console.error('登录码为空，停止轮询');
                    clearInterval(loginPollingInterval);
                    loginPollingInterval = null;
                    return;
                }
                
                const response = await fetch(`https://tapi.xuejss.com/xue/user/getWeiXinIsLogin?loginCode=${currentLoginCode}`);
                const result = await response.json();
                
                console.log('轮询结果:', result); // 添加调试日志
                
                // 检查登录状态 - 根据API文档，登录成功时code为200
                if (result.code === 200 && result.data) {
                    // 登录成功
                    clearInterval(loginPollingInterval);
                    loginPollingInterval = null;
                    
                    // 保存用户信息
                    const userInfo = {
                        username: result.data.username || '未知用户',
                        userid: result.data.userid || '未知ID',
                        token: result.data.token || '无token',
                        loginTime: new Date().toISOString()
                    };
                    
                    // 保存到本地存储
                    saveUserInfo(userInfo);
                } else if (result.code === 0 || (result.code === 200 && !result.data)) {
                    // 未登录，继续轮询
                    document.getElementById('login-status').textContent = '等待扫描或确认登录...';
                } else {
                    // 其他状态，显示错误信息
                    document.getElementById('login-status').textContent = result.msg || '登录状态未知';
                }
            } catch (error) {
                console.error('轮询登录状态失败:', error);
                document.getElementById('login-status').textContent = '检查登录状态失败，请重试';
            }
        }, 3000);
    }
    
    // 显示登录成功界面
    function showLoginSuccess(userInfo) {
        const qrcodeContainer = document.getElementById('qrcode-container');
        const qrcodeImage = document.getElementById('qrcode-image');
        const loginSuccess = document.getElementById('login-success');
        
        // 隐藏所有登录相关界面
        qrcodeContainer.classList.add('hidden');
        qrcodeImage.classList.add('hidden');
        
        // 显示登录成功界面
        loginSuccess.classList.remove('hidden');
        
        document.getElementById('user-info').innerHTML = `
            <p><strong>用户名:</strong> ${userInfo.username}</p>
            <p><strong>用户ID:</strong> ${userInfo.userid}</p>
            <p><strong>登录时间:</strong> ${new Date(userInfo.loginTime).toLocaleString()}</p>
        `;
        
        showMessage('微信登录成功', 'success');
    }
    
    // 退出登录
    function logout() {
        // 清除轮询
        if (loginPollingInterval) {
            clearInterval(loginPollingInterval);
            loginPollingInterval = null;
        }
        
        // 清除本地存储
        clearUserInfo(() => {
            // 重置界面
            document.getElementById('qrcode-container').classList.remove('hidden');
            document.getElementById('qrcode-image').classList.add('hidden');
            document.getElementById('login-success').classList.add('hidden');
            
            // 清除登录码
            currentLoginCode = null;
            
            showMessage('已退出登录', 'success');
        });
    }
    
    // 检查是否已登录
    function checkLoginStatus() {
        getUserInfo((userInfo) => {
            if (userInfo) {
                showLoginSuccess(userInfo);
            }
        });
    }
    
    // 初始化时检查登录状态
    checkLoginStatus();
    
    // 说说功能
    const momentContent = document.getElementById('moment-content');
    const charCount = document.getElementById('char-count');
    const addMomentBtn = document.getElementById('add-moment-btn');
    const filterMoments = document.getElementById('filter-moments');
    const clearAllMomentsBtn = document.getElementById('clear-all-moments');
    const momentsList = document.getElementById('moments-list');
    
    // 字符计数
    momentContent.addEventListener('input', () => {
        const length = momentContent.value.length;
        charCount.textContent = `${length}/500`;
    });
    
    // 添加说说
    addMomentBtn.addEventListener('click', () => {
        const content = momentContent.value.trim();
        if (!content) {
            showMessage('请输入说说内容', 'error');
            return;
        }
        
        const moment = {
            id: Date.now(),
            content: content,
            timestamp: new Date().toISOString(),
            date: new Date().toLocaleDateString()
        };
        
        // 保存说说
        saveMoment(moment);
        
        // 清空输入框
        momentContent.value = '';
        charCount.textContent = '0/500';
        
        // 刷新说说列表
        loadMoments();
        
        showMessage('说说发布成功', 'success');
    });
    
    // 过滤说说
    filterMoments.addEventListener('change', () => {
        loadMoments();
    });
    
    // 清空所有说说
    clearAllMomentsBtn.addEventListener('click', () => {
        if (confirm('确定要清空所有说说吗？此操作不可恢复！')) {
            clearAllMoments();
            showMessage('已清空所有说说', 'success');
        }
    });
    
    // 保存说说到本地存储
    function saveMoment(moment) {
        const moments = getMoments();
        moments.unshift(moment); // 新说说添加到开头
        localStorage.setItem('moments', JSON.stringify(moments));
    }
    
    // 获取所有说说
    function getMoments() {
        try {
            const moments = localStorage.getItem('moments');
            return moments ? JSON.parse(moments) : [];
        } catch (error) {
            console.error('获取说说失败:', error);
            return [];
        }
    }
    
    // 清空所有说说
    function clearAllMoments() {
        localStorage.removeItem('moments');
        loadMoments();
    }
    
    // 加载并显示说说
    function loadMoments() {
        const moments = getMoments();
        const filter = filterMoments.value;
        
        // 根据过滤条件筛选说说
        let filteredMoments = moments;
        const now = new Date();
        
        if (filter === 'today') {
            const today = now.toLocaleDateString();
            filteredMoments = moments.filter(moment => moment.date === today);
        } else if (filter === 'week') {
            const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
            filteredMoments = moments.filter(moment => new Date(moment.timestamp) >= weekAgo);
        } else if (filter === 'month') {
            const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
            filteredMoments = moments.filter(moment => new Date(moment.timestamp) >= monthAgo);
        }
        
        // 显示说说
        displayMoments(filteredMoments);
    }
    
    // 显示说说列表
    function displayMoments(moments) {
        if (moments.length === 0) {
            momentsList.innerHTML = `
                <div class="empty-state">
                    <p>还没有说说，开始记录你的第一条想法吧！</p>
                </div>
            `;
            return;
        }
        
        momentsList.innerHTML = '';
        
        moments.forEach(moment => {
            const momentEl = document.createElement('div');
            momentEl.className = 'moment-item';
            
            const date = new Date(moment.timestamp);
            const formattedDate = date.toLocaleDateString();
            const formattedTime = date.toLocaleTimeString();
            
            momentEl.innerHTML = `
                <div class="moment-content">${escapeHtml(moment.content)}</div>
                <div class="moment-footer">
                    <span class="moment-time">${formattedDate} ${formattedTime}</span>
                    <button class="delete-moment-btn" data-id="${moment.id}">删除</button>
                </div>
            `;
            
            momentsList.appendChild(momentEl);
        });
        
        // 添加删除按钮事件
        document.querySelectorAll('.delete-moment-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const id = parseInt(e.target.getAttribute('data-id'));
                deleteMoment(id);
            });
        });
    }
    
    // 删除说说
    function deleteMoment(id) {
        let moments = getMoments();
        moments = moments.filter(moment => moment.id !== id);
        localStorage.setItem('moments', JSON.stringify(moments));
        loadMoments();
        showMessage('说说已删除', 'success');
    }
    
    // HTML转义函数，防止XSS攻击
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    // 初始化说说列表
    loadMoments();
    
    // 为所有按钮添加波纹效果
    document.addEventListener('click', function(e) {
        const target = e.target;
        if (target.tagName === 'BUTTON' && !target.classList.contains('no-ripple')) {
            createRipple(target, e);
        }
    });
    
    // 创建波纹效果
    function createRipple(button, event) {
        const ripple = document.createElement('span');
        ripple.classList.add('ripple');
        
        const rect = button.getBoundingClientRect();
        const size = Math.max(rect.width, rect.height);
        const x = event.clientX - rect.left - size / 2;
        const y = event.clientY - rect.top - size / 2;
        
        ripple.style.width = ripple.style.height = size + 'px';
        ripple.style.left = x + 'px';
        ripple.style.top = y + 'px';
        
        button.appendChild(ripple);
        
        setTimeout(() => {
            ripple.remove();
        }, 600);
    }
    
    // 文件版本: 2023-10-31-08-30 - 修复CSP错误和Chrome API兼容性问题
    console.log('popup.js 已加载 - 版本: 2023-10-31-08-30');
});